import Link from 'next/link'; import { notFound, redirect } from 'next/navigation'; import { getCustomerUser } from '@/app/lib/lumen-auth'; import { commerceDb } from '@/app/lib/commerce-db'; import { displayOrderId } from '@/app/lib/orders'; import { STYLE_CATALOG } from '@/app/data/styleCatalog'; import { BACKGROUND_COLORS } from '@/app/data/backgrounds'; import { PRODUCTS, sizeLabel, type Orientation } from '@/app/lib/pricing'; import { FramedPreview } from '@/app/components/FramedPreview'; import type { FrameId } from '@/app/data/frames'; import { CancelButton } from './cancel-button'; import { OrderConversation } from '@/app/components/OrderConversation'; import { CustomerOrderMessageForm } from '@/app/components/CustomerOrderMessageForm'; import { orderConversation, STUDIO_MESSAGE_STATUSES } from '@/app/lib/order-messages'; import { REVIEWABLE_STATUSES } from '@/app/lib/reviews'; import { ReviewForm } from './review-form'; export const dynamic = 'force-dynamic'; // Label maps for the picker-time selections stored in order.config. // Kept inline here to avoid pulling the Builder's full FRAME/MATTE/FONT // definitions (which carry gradients + font CSS) into a server bundle // that only needs labels. const FRAME_LABELS: Record = { black: 'Matte black', white: 'Soft white', walnut: 'Walnut', oak: 'Honey oak', gold: 'Warm gold', silver: 'Brushed silver', }; const MATTE_LABELS: Record = { snowwhite: 'Snow white', offwhite: 'Off-white', black: 'Black', // Legacy values that may exist on older orders: warmwhite: 'Off-white', // renamed hayseed: 'Off-white', cream: 'Off-white', none: 'Snow white', }; const FONT_LABELS: Record = { modern: 'Modern', editorial: 'Editorial', display: 'Display', italic: 'Italic', serif: 'Classic', script: 'Script', hand: 'Handwritten', soft: 'Soft sans', }; type OrderConfig = { workflow?: string; styleId?: string; productId?: 'matted' | 'canvas' | 'classic' | 'stretched'; size?: string; orientation?: Orientation; frame?: string; matteId?: string; bgColorId?: string; bgCustom?: string; fontId?: string; includeName?: boolean; commissionName?: string | null; artistNote?: string; pets?: Array<{ slot: number; name: string | null }>; customerCancellation?: { state?: 'pending' | 'refunded' | 'unpaid' }; }; export default async function OrderDetailPage( { params, searchParams }: { params: Promise<{ id: string }>; searchParams: Promise<{ revised?: string }> }, ) { const { id } = await params; const { revised } = await searchParams; const user = await getCustomerUser(); if (!user) redirect(`/login?next=/orders/${id}`); const admin = commerceDb(); const { data: order } = await admin .from('orders') .select('*') .eq('id', id) .single(); if (!order) notFound(); if (order.user_id !== user.id) notFound(); // pending_payment / abandoned are pre-studio rows where Stripe was // never completed. Send the customer to the resume-payment screen // so they can pay (or back out) instead of staring at a useless // detail page. const cfg = (order.config as OrderConfig | null) ?? {}; const selfServicePrint = cfg.workflow === 'self_service_print_v1'; if (!selfServicePrint && (order.status === 'pending_payment' || order.status === 'abandoned')) { redirect(`/checkout?orderId=${order.id}&canceled=1`); } // Once the customer has approved (status >= approved), show the // actual final framed artwork on the order detail page. const POST_APPROVAL_STATUSES = new Set(['approved', 'fulfillment_submitting', 'fulfillment_review', 'in_production', 'shipped']); let approvedCleanUrl: string | null = null; if (POST_APPROVAL_STATUSES.has(order.status as string) && order.current_generation_id) { const { data: gen } = await admin .from('generations') .select('clean_url') .eq('id', order.current_generation_id) .single(); approvedCleanUrl = gen?.clean_url ?? null; } const status = order.status as string; const reviewable = REVIEWABLE_STATUSES.includes(status); const review = reviewable ? await admin.from('order_reviews').select('status').eq('order_id', order.id).maybeSingle() : null; const style = STYLE_CATALOG.find(s => s.id === cfg.styleId); const product = cfg.productId ? PRODUCTS[cfg.productId] : null; const sizes = product?.sizes as Record | undefined; const sizeMeta = sizes && cfg.size ? sizes[cfg.size] : undefined; const orientation = cfg.orientation ?? 'portrait'; // Transposed for landscape orders ('10 × 8 in'); sizeMeta stays the // existence check, sizeLabelStr is what we display. const sizeLabelStr = sizeLabel(cfg.productId, cfg.size, orientation); const frameLabel = cfg.frame ? FRAME_LABELS[cfg.frame] : null; const hasMatOption = cfg.productId === 'matted' || cfg.productId === 'classic'; const matteLabel = hasMatOption && cfg.matteId ? cfg.matteId === 'nomat' ? 'No mat' : MATTE_LABELS[cfg.matteId] : null; const cancellationState = cfg.customerCancellation?.state; const bgLabel = cfg.bgColorId === 'custom' ? (cfg.bgCustom || 'Custom') : (cfg.bgColorId ? BACKGROUND_COLORS[cfg.bgColorId as keyof typeof BACKGROUND_COLORS]?.label : null); const fontLabel = cfg.includeName && cfg.fontId ? FONT_LABELS[cfg.fontId] : null; const petNames = (cfg.pets ?? []).map(p => p.name).filter((n): n is string => !!n); const photos = (order.pet_photo_urls as string[]) ?? []; const customStyleUrl = (order.custom_style_url as string | null) ?? null; const artistNote = (cfg.artistNote ?? '').trim(); const messages = orderConversation(order.config, order.revision_note, order.updated_at); const canMessage = STUDIO_MESSAGE_STATUSES.includes(status); return (
← All commissions

{displayOrderId(order.id)}

{statusLabel(status)}

{status === 'cancelled' ? cancellationState === 'pending' ? 'Your commission is cancelled. Your refund has not been confirmed yet.' : cancellationState === 'refunded' ? 'Your commission is cancelled and a refund has been requested.' : 'Your commission is cancelled.' : selfServicePrint && status === 'pending_payment' ? 'We haven’t confirmed payment yet. If you already paid, do not pay again. Refresh this page in a moment to check the status.' : statusBody(status, order.id)}

{status === 'shipped' && (order.tracking_number || order.tracking_url) && (

{order.carrier ? `${order.carrier} · ` : ''} {order.tracking_number ? {order.tracking_number} : null} {order.tracking_url ? ( <> {' '}·{' '} Track shipment → ) : null}

)} {status === 'awaiting_approval' && (
Review your proof →
)} {(status === 'pending_design' || status === 'awaiting_approval' || status === 'revision_requested' || status === 'cancelled' && cancellationState === 'pending') && ( )} {status === 'cancelled' && photos.length > 0 &&
Start a replacement {' '}Saved photos
}
{(messages.length > 0 || canMessage) && (
{canMessage && } {status === 'revision_requested' && revised === 'saved' && (

Your request is saved here. We couldn’t email the studio a notification.

)}
)} {reviewable && (

Leave a review

{review?.error ?

Reviews are temporarily unavailable. Please try again later.

: review?.data ?

{review.data.status === 'approved' ? 'Thank you. Your review is published.' : 'Thank you. We’ve received your review.'}

: }
)} {approvedCleanUrl && (

Your approved portrait, mocked up in your chosen{' '} {product?.label ?? 'frame'}{sizeMeta ? `, ${sizeLabelStr}` : ''}.

)}
{customStyleUrl ? (
Style Custom — your reference
) : style ? (
Style {style.name}
) : null} {product && sizeMeta && (
Product {product.label}, {sizeLabelStr}
)} {frameLabel && (
Frame {frameLabel}
)} {matteLabel && (
Mount {matteLabel}
)} {bgLabel && (
Background {bgLabel}
)} {cfg.includeName && cfg.commissionName && (
Lettering “{cfg.commissionName}”{fontLabel ? ` · ${fontLabel}` : ''}
)} {petNames.length > 0 && (
{petNames.length === 1 ? 'Pet' : 'Pets'} {petNames.join(', ')}
)}
Portrait subtotal ${(order.price_cents / 100).toFixed(2)}
Submitted {new Date(order.created_at).toLocaleString()}
{photos.length > 0 && (
Photos you sent · {photos.length}
)} {customStyleUrl && ( )} {artistNote && (

Your note to the artist “{artistNote}”

)}
); } function statusLabel(s: string): string { switch (s) { // pending_payment / abandoned redirect to /checkout before render, // but label them in case a future code path lands here. case 'pending_payment': return 'Checkout not complete'; case 'abandoned': return 'Checkout abandoned'; case 'pending_design': return 'In the design queue'; case 'awaiting_approval': return 'Proof ready — review'; case 'revision_requested': return 'Revision in progress'; case 'approved': return 'Approved — final studio review'; case 'fulfillment_submitting': return 'Payment received · sending to printer'; case 'fulfillment_review': return 'Payment received · checking print order'; case 'in_production': return 'In production'; case 'shipped': return 'Shipped'; case 'cancelled': return 'Cancelled'; default: return s; } } function statusBody(status: string, _orderId: string): string { switch (status) { case 'pending_payment': return "We haven't received payment yet. Head back to checkout to finish — your design selections are saved."; case 'abandoned': return "Checkout was never completed. Head back to checkout to pick up where you left off — or start a fresh commission."; case 'pending_design': return "Our studio is hand-crafting your proof. We typically have a first draft ready within 24 hours — we'll email you when it's time to review."; case 'awaiting_approval': return "Your proof is ready. Open it to approve and pay, or request revisions — free, until it's right."; case 'revision_requested': return "We're working on your revision. Expect another proof within 24 hours."; case 'approved': return "You approved your portrait — our studio is doing one final review before sending it to print. You'll get a confirmation email when it goes to the printer."; case 'fulfillment_submitting': return "Payment is confirmed. We’re sending the exact image you approved to the printer."; case 'fulfillment_review': return "Payment is confirmed. We couldn’t verify printer acceptance yet. Don’t place a second order."; case 'in_production': return "Your portrait is being printed and framed. Ships within 10 days."; case 'shipped': return "On the way to you."; case 'cancelled': return "This commission was cancelled and a full refund is on its way back to your card. Refunds typically take 5–10 business days to land."; default: return ''; } }